using AutoMapper;
using CodeSpirit.Core.DependencyInjection;
using CodeSpirit.LLM;
using CodeSpirit.SurveyApi.Dtos.Question;
using CodeSpirit.SurveyApi.Dtos.Survey;
using CodeSpirit.SurveyApi.Models;
using CodeSpirit.SurveyApi.Models.Enums;
using CodeSpirit.SurveyApi.Services.Interfaces;
using CodeSpirit.Shared.Services;
using Newtonsoft.Json;
using System.Text;
using System.Text.RegularExpressions;

namespace CodeSpirit.SurveyApi.Services.Implementations;

/// <summary>
/// 问卷LLM生成服务实现
/// </summary>
public class SurveyLLMGeneratorService : ISurveyLLMGeneratorService, IScopedDependency
{
    private readonly LLMAssistant _llmAssistant;
    private readonly ISurveySettingsService _settingsService;
    private readonly ISurveyService _surveyService;
    private readonly IQuestionService _questionService;
    private readonly IMapper _mapper;
    private readonly ILogger<SurveyLLMGeneratorService> _logger;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="llmAssistant">LLM助手</param>
    /// <param name="settingsService">设置服务</param>
    /// <param name="surveyService">问卷服务</param>
    /// <param name="questionService">题目服务</param>
    /// <param name="mapper">映射器</param>
    /// <param name="logger">日志器</param>
    /// <param name="currentUser">当前用户</param>
    public SurveyLLMGeneratorService(
        LLMAssistant llmAssistant,
        ISurveySettingsService settingsService,
        ISurveyService surveyService,
        IQuestionService questionService,
        IMapper mapper,
        ILogger<SurveyLLMGeneratorService> logger,
        ICurrentUser currentUser)
    {
        _llmAssistant = llmAssistant;
        _settingsService = settingsService;
        _surveyService = surveyService;
        _questionService = questionService;
        _mapper = mapper;
        _logger = logger;
        _currentUser = currentUser;
    }

    /// <summary>
    /// 根据主题生成问卷字段建议
    /// </summary>
    /// <param name="topic">问卷主题</param>
    /// <returns>字段建议</returns>
    public async Task<SurveyFieldSuggestions> GenerateFieldSuggestionsAsync(string topic)
    {
        try
        {
            _logger.LogInformation("开始生成问卷字段建议，主题：{Topic}", topic);

            // 获取LLM设置
            var llmSettings = await _settingsService.GetLLMSettingsAsync();

            // 构建字段建议的提示词
            var prompt = BuildFieldSuggestionsPrompt(topic);

            // 调用LLM生成建议
            var llmResponse = await _llmAssistant.GenerateContentAsync(prompt, 1000); // 使用较少的tokens

            // 解析LLM响应为字段建议
            var suggestions = ParseFieldSuggestionsResponse(llmResponse);

            _logger.LogInformation("问卷字段建议生成成功");

            return suggestions;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成问卷字段建议失败，主题：{Topic}", topic);
            throw new BusinessException($"生成问卷字段建议失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 根据主题生成问卷
    /// </summary>
    /// <param name="request">生成请求</param>
    /// <returns>生成的问卷</returns>
    public async Task<GeneratedSurveyDto> GenerateSurveyAsync(GenerateSurveyRequest request)
    {
        try
        {
            _logger.LogInformation("开始生成问卷，主题：{Topic}", request.Topic);

            // 获取LLM设置
            var llmSettings = await _settingsService.GetLLMSettingsAsync();

            // 构建提示词
            var prompt = await BuildSurveyGenerationPromptAsync(request);

            // 验证提示词长度
            var validationResult = await ValidatePromptAsync(prompt);
            if (!validationResult.IsValid)
            {
                if (validationResult.NeedsCompression)
                {
                    prompt = await CompressPromptAsync(prompt, llmSettings.MaxPromptLength);
                }
                else
                {
                    throw new BusinessException($"提示词验证失败：{validationResult.Message}");
                }
            }

            // 调用LLM生成内容
            var llmResponse = await _llmAssistant.GenerateContentAsync(prompt, llmSettings.MaxTokens);

            // 解析LLM响应
            var generatedSurvey = await ParseLLMResponseAsync(llmResponse, request, prompt);

            _logger.LogInformation("问卷生成成功，题目数量：{QuestionCount}", generatedSurvey.Questions.Count);

            // 保存生成的问卷及题目
            var savedSurvey = await SaveGeneratedSurveyAsync(generatedSurvey, request, llmResponse);
            
            // 更新生成结果，添加保存后的问卷ID
            generatedSurvey.SavedSurveyId = savedSurvey.Id;

            return generatedSurvey;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成问卷失败，主题：{Topic}", request.Topic);
            throw new BusinessException($"生成问卷失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 优化现有问卷
    /// </summary>
    /// <param name="surveyId">问卷ID</param>
    /// <param name="optimizationGoals">优化目标</param>
    /// <returns>优化建议</returns>
    public async Task<SurveyOptimizationResult> OptimizeSurveyAsync(int surveyId, string optimizationGoals)
    {
        try
        {
            _logger.LogInformation("开始优化问卷 {SurveyId}，优化目标：{Goals}", surveyId, optimizationGoals);

            // TODO: 获取现有问卷数据
            // var survey = await _surveyService.GetAsync(surveyId);

            // 构建优化提示词
            var prompt = BuildOptimizationPrompt(surveyId, optimizationGoals);

            // 调用LLM生成优化建议
            var llmResponse = await _llmAssistant.GenerateContentAsync(prompt);

            // 解析优化建议
            var result = ParseOptimizationResponse(llmResponse);

            _logger.LogInformation("问卷优化完成，建议数量：{SuggestionCount}", result.Suggestions.Count);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "优化问卷失败，ID：{SurveyId}", surveyId);
            throw new BusinessException($"优化问卷失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 生成问卷洞察分析
    /// </summary>
    /// <param name="surveyDto">问卷信息</param>
    /// <returns>洞察分析结果</returns>
    public async Task<SurveyInsightResult> GenerateInsightsAsync(SurveyDto surveyDto)
    {
        try
        {
            _logger.LogInformation("开始生成问卷洞察分析 {SurveyId} - {SurveyTitle}", surveyDto.Id, surveyDto.Title);

            // 检查是否启用洞察功能
            var llmSettings = await _settingsService.GetLLMSettingsAsync();
            if (!llmSettings.EnableInsights)
            {
                throw new BusinessException("LLM洞察分析功能已禁用");
            }

            // 获取问卷题目数据
            var questions = await _questionService.GetQuestionsBySurveyIdAsync(surveyDto.Id);

            // 构建洞察分析提示词
            var prompt = BuildInsightPrompt(surveyDto, questions);

            // 调用LLM生成洞察
            var llmResponse = await _llmAssistant.GenerateContentAsync(prompt);

            // 解析洞察结果
            var result = ParseInsightResponse(llmResponse, surveyDto);

            _logger.LogInformation("问卷洞察分析完成，问卷：{SurveyTitle}", surveyDto.Title);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成问卷洞察失败，ID：{SurveyId}", surveyDto.Id);
            throw new BusinessException($"生成洞察失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 验证提示词长度
    /// </summary>
    /// <param name="prompt">提示词</param>
    /// <returns>验证结果</returns>
    public async Task<PromptValidationResult> ValidatePromptAsync(string prompt)
    {
        if (string.IsNullOrEmpty(prompt))
        {
            return new PromptValidationResult
            {
                IsValid = false,
                Length = 0,
                EstimatedTokens = 0,
                Message = "提示词不能为空"
            };
        }

        var llmSettings = await _settingsService.GetLLMSettingsAsync();
        var length = prompt.Length;
        var estimatedTokens = EstimateTokenCount(prompt);

        var result = new PromptValidationResult
        {
            Length = length,
            EstimatedTokens = estimatedTokens
        };

        if (length > llmSettings.MaxPromptLength)
        {
            result.IsValid = false;
            result.NeedsCompression = true;
            result.Message = $"提示词长度超过限制（{length} > {llmSettings.MaxPromptLength}），建议压缩";
        }
        else if (estimatedTokens > llmSettings.MaxTokens * 0.8) // 预留20%的Token给响应
        {
            result.IsValid = false;
            result.NeedsCompression = true;
            result.Message = $"预估Token数过多（{estimatedTokens} > {llmSettings.MaxTokens * 0.8}），建议压缩";
        }
        else
        {
            result.IsValid = true;
            result.Message = "提示词验证通过";
        }

        return result;
    }

    /// <summary>
    /// 压缩提示词
    /// </summary>
    /// <param name="prompt">原始提示词</param>
    /// <param name="maxLength">最大长度</param>
    /// <returns>压缩后的提示词</returns>
    public Task<string> CompressPromptAsync(string prompt, int maxLength)
    {
        if (prompt.Length <= maxLength)
        {
            return Task.FromResult(prompt);
        }

        _logger.LogInformation("开始压缩提示词，原长度：{OriginalLength}，目标长度：{MaxLength}", 
            prompt.Length, maxLength);

        // 简单的压缩策略：移除多余的空白字符和换行
        var compressed = Regex.Replace(prompt, @"\s+", " ").Trim();
        
        // 如果还是太长，截断到最大长度
        if (compressed.Length > maxLength)
        {
            compressed = compressed.Substring(0, maxLength - 3) + "...";
        }

        _logger.LogInformation("提示词压缩完成，压缩后长度：{CompressedLength}", compressed.Length);

        return Task.FromResult(compressed);
    }

    #region 私有辅助方法

    /// <summary>
    /// 构建字段建议提示词
    /// </summary>
    /// <param name="topic">问卷主题</param>
    /// <returns>提示词</returns>
    private string BuildFieldSuggestionsPrompt(string topic)
    {
        var prompt = $@"基于问卷主题""{topic}""，请为问卷生成以下字段的建议：

1. 问卷描述：简明扼要地描述问卷的目的和背景
2. 问卷类型：例如满意度调查、市场调研、员工反馈等
3. 题目数量：建议的题目数量（5-20题范围内）
4. 目标受众：描述问卷的目标受众群体
5. 调查目标：明确说明通过此问卷希望达到的目标

请以JSON格式回复，格式如下：
{{
  ""description"": ""问卷描述"",
  ""surveyType"": ""问卷类型"",
  ""questionCount"": 题目数量,
  ""targetAudience"": ""目标受众"",
  ""goals"": ""调查目标""
}}

要求：
- 内容要与主题高度相关
- 描述要简洁明了
- 题目数量要合理
- 目标受众要具体
- 调查目标要明确可执行";

        return prompt;
    }

    /// <summary>
    /// 解析字段建议响应
    /// </summary>
    /// <param name="llmResponse">LLM响应</param>
    /// <returns>字段建议</returns>
    private SurveyFieldSuggestions ParseFieldSuggestionsResponse(string llmResponse)
    {
        try
        {
            // 提取JSON部分
            var jsonMatch = Regex.Match(llmResponse, @"\{[\s\S]*\}", RegexOptions.Multiline);
            if (!jsonMatch.Success)
            {
                throw new ArgumentException("无法从响应中提取JSON格式的建议");
            }

            var jsonContent = jsonMatch.Value;
            var suggestions = JsonConvert.DeserializeObject<SurveyFieldSuggestions>(jsonContent);

            if (suggestions == null)
            {
                throw new ArgumentException("JSON解析失败");
            }

            // 验证和调整数据
            if (suggestions.QuestionCount < 1 || suggestions.QuestionCount > 50)
            {
                suggestions.QuestionCount = 10; // 默认值
            }

            return suggestions;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "解析字段建议失败，使用默认建议。LLM响应：{Response}", llmResponse);
            
            // 返回默认建议
            return new SurveyFieldSuggestions
            {
                Description = "这是一份调查问卷，旨在收集相关信息和意见。",
                SurveyType = "意见调查",
                QuestionCount = 10,
                TargetAudience = "相关人群",
                Goals = "了解具体情况，收集意见和建议，为后续决策提供数据支持。"
            };
        }
    }

    /// <summary>
    /// 构建问卷生成提示词
    /// </summary>
    /// <param name="request">生成请求</param>
    /// <returns>提示词</returns>
    private Task<string> BuildSurveyGenerationPromptAsync(GenerateSurveyRequest request)
    {
        var promptBuilder = new StringBuilder();

        promptBuilder.AppendLine("你是一个专业的问卷设计专家，请根据以下要求生成一份问卷：");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine($"问卷主题：{request.Topic}");
        
        if (!string.IsNullOrEmpty(request.Description))
        {
            promptBuilder.AppendLine($"问卷描述：{request.Description}");
        }
        
        if (!string.IsNullOrEmpty(request.SurveyType))
        {
            promptBuilder.AppendLine($"问卷类型：{request.SurveyType}");
        }
        
        promptBuilder.AppendLine($"题目数量：{request.QuestionCount}");
        
        if (!string.IsNullOrEmpty(request.TargetAudience))
        {
            promptBuilder.AppendLine($"目标受众：{request.TargetAudience}");
        }
        
        if (!string.IsNullOrEmpty(request.Goals))
        {
            promptBuilder.AppendLine($"调查目标：{request.Goals}");
        }

        promptBuilder.AppendLine();
        promptBuilder.AppendLine("请按照以下JSON格式返回问卷数据：");
        promptBuilder.AppendLine("{");
        promptBuilder.AppendLine("  \"title\": \"问卷标题\",");
        promptBuilder.AppendLine("  \"description\": \"问卷描述\",");
        promptBuilder.AppendLine("  \"questions\": [");
        promptBuilder.AppendLine("    {");
        promptBuilder.AppendLine("      \"title\": \"题目标题\",");
        promptBuilder.AppendLine("      \"description\": \"题目描述（可选）\",");
        promptBuilder.AppendLine("      \"type\": \"题目类型（SingleChoice/MultipleChoice/Text/TextArea/Number/Date等）\",");
        promptBuilder.AppendLine("      \"isRequired\": true/false,");
        promptBuilder.AppendLine("      \"orderIndex\": 排序索引,");
        promptBuilder.AppendLine("      \"options\": [");
        promptBuilder.AppendLine("        {");
        promptBuilder.AppendLine("          \"text\": \"选项文本\",");
        promptBuilder.AppendLine("          \"value\": \"选项值\",");
        promptBuilder.AppendLine("          \"orderIndex\": 排序索引");
        promptBuilder.AppendLine("        }");
        promptBuilder.AppendLine("      ]");
        promptBuilder.AppendLine("    }");
        promptBuilder.AppendLine("  ]");
        promptBuilder.AppendLine("}");

        if (!string.IsNullOrEmpty(request.CustomPrompt))
        {
            promptBuilder.AppendLine();
            promptBuilder.AppendLine("额外要求：");
            promptBuilder.AppendLine(request.CustomPrompt);
        }

        return Task.FromResult(promptBuilder.ToString());
    }

    /// <summary>
    /// 构建优化提示词
    /// </summary>
    /// <param name="surveyId">问卷ID</param>
    /// <param name="optimizationGoals">优化目标</param>
    /// <returns>提示词</returns>
    private string BuildOptimizationPrompt(int surveyId, string optimizationGoals)
    {
        var promptBuilder = new StringBuilder();
        
        promptBuilder.AppendLine("你是一个问卷优化专家，请分析以下问卷并提供优化建议：");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine($"问卷ID：{surveyId}");
        promptBuilder.AppendLine($"优化目标：{optimizationGoals}");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("请从以下角度分析并提供建议：");
        promptBuilder.AppendLine("1. 题目设计的合理性");
        promptBuilder.AppendLine("2. 选项设置的完整性");
        promptBuilder.AppendLine("3. 问卷结构的逻辑性");
        promptBuilder.AppendLine("4. 用户体验的友好性");
        promptBuilder.AppendLine("5. 数据收集的有效性");

        return promptBuilder.ToString();
    }

    /// <summary>
    /// 构建洞察分析提示词
    /// </summary>
    /// <param name="surveyDto">问卷信息</param>
    /// <param name="questions">问卷题目列表</param>
    /// <returns>提示词</returns>
    private string BuildInsightPrompt(SurveyDto surveyDto, List<QuestionDto> questions)
    {
        var promptBuilder = new StringBuilder();
        
        promptBuilder.AppendLine("你是一个专业的问卷数据分析专家，请基于以下问卷信息提供深度洞察分析：");
        promptBuilder.AppendLine();
        
        // 问卷基本信息
        promptBuilder.AppendLine("## 问卷基本信息");
        promptBuilder.AppendLine($"- 问卷标题：{surveyDto.Title}");
        if (!string.IsNullOrEmpty(surveyDto.Description))
        {
            promptBuilder.AppendLine($"- 问卷描述：{surveyDto.Description}");
        }
        promptBuilder.AppendLine($"- 问卷状态：{surveyDto.Status}");
        promptBuilder.AppendLine($"- 题目数量：{surveyDto.QuestionCount}");
        promptBuilder.AppendLine($"- 回答数量：{surveyDto.ResponseCount}");
        promptBuilder.AppendLine($"- 创建时间：{surveyDto.CreatedAt:yyyy-MM-dd}");
        if (surveyDto.PublishedAt.HasValue)
        {
            promptBuilder.AppendLine($"- 发布时间：{surveyDto.PublishedAt:yyyy-MM-dd}");
        }
        promptBuilder.AppendLine();
        
        // 题目结构信息
        if (questions.Any())
        {
            promptBuilder.AppendLine("## 题目结构");
            for (int i = 0; i < questions.Count && i < 10; i++) // 限制显示前10个题目
            {
                var question = questions[i];
                promptBuilder.AppendLine($"{i + 1}. [{question.Type}] {question.Title}");
                if (!string.IsNullOrEmpty(question.Description))
                {
                    promptBuilder.AppendLine($"   描述：{question.Description}");
                }
                promptBuilder.AppendLine($"   必填：{(question.IsRequired ? "是" : "否")}");
            }
            if (questions.Count > 10)
            {
                promptBuilder.AppendLine($"... 还有 {questions.Count - 10} 个题目");
            }
            promptBuilder.AppendLine();
        }
        
        promptBuilder.AppendLine("## 分析要求");
        promptBuilder.AppendLine("请从以下维度进行深度分析，并提供结构化的洞察报告：");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("### 1. 问卷设计质量分析");
        promptBuilder.AppendLine("- 题目设计的合理性和逻辑性");
        promptBuilder.AppendLine("- 题目类型分布是否均衡");
        promptBuilder.AppendLine("- 必填题设置是否合理");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("### 2. 数据收集效果评估");
        promptBuilder.AppendLine("- 回答率和参与度分析");
        promptBuilder.AppendLine("- 数据质量评估");
        promptBuilder.AppendLine("- 潜在的数据偏差或问题");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("### 3. 优化建议");
        promptBuilder.AppendLine("- 问卷结构优化建议");
        promptBuilder.AppendLine("- 题目改进建议");
        promptBuilder.AppendLine("- 数据收集策略建议");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("### 4. 关键洞察");
        promptBuilder.AppendLine("- 主要发现和趋势");
        promptBuilder.AppendLine("- 值得关注的模式");
        promptBuilder.AppendLine("- 行动建议");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("请用中文提供详细、专业且易于理解的分析报告。");

        return promptBuilder.ToString();
    }

    /// <summary>
    /// 解析LLM响应为问卷数据
    /// </summary>
    /// <param name="llmResponse">LLM响应</param>
    /// <param name="request">原始请求</param>
    /// <param name="usedPrompt">使用的完整提示词</param>
    /// <returns>生成的问卷</returns>
    private Task<GeneratedSurveyDto> ParseLLMResponseAsync(string llmResponse, GenerateSurveyRequest request, string usedPrompt)
    {
        try
        {
            // 尝试从响应中提取JSON
            var jsonMatch = Regex.Match(llmResponse, @"\{[\s\S]*\}", RegexOptions.Multiline);
            var jsonContent = jsonMatch.Success ? jsonMatch.Value : llmResponse;

            // 解析JSON
            var surveyData = JsonConvert.DeserializeObject<dynamic>(jsonContent);

            var result = new GeneratedSurveyDto
            {
                Title = surveyData?.title ?? request.Topic ?? "未知主题",
                Description = surveyData?.description ?? request.Description,
                Questions = new List<GeneratedQuestionDto>(),
                UsedPrompt = usedPrompt,
                GeneratedAt = DateTime.UtcNow,
                QualityScore = CalculateQualityScore(surveyData)
            };

            // 解析题目
            if (surveyData?.questions != null)
            {
                int orderIndex = 1;
                foreach (var questionData in surveyData.questions)
                {
                    var question = new GeneratedQuestionDto
                    {
                        Title = questionData?.title ?? "",
                        Description = questionData?.description,
                        Type = questionData?.type ?? "Text",
                        IsRequired = questionData?.isRequired ?? false,
                        OrderIndex = orderIndex++,
                        Options = new List<GeneratedQuestionOptionDto>()
                    };

                    // 解析选项
                    if (questionData?.options != null)
                    {
                        int optionIndex = 1;
                        foreach (var optionData in questionData.options)
                        {
                            question.Options.Add(new GeneratedQuestionOptionDto
                            {
                                Text = optionData?.text ?? "",
                                Value = optionData?.value,
                                OrderIndex = optionIndex++
                            });
                        }
                    }

                    result.Questions.Add(question);
                }
            }

            return Task.FromResult(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "解析LLM响应失败");
            
            // 返回默认结果
            return Task.FromResult(new GeneratedSurveyDto
            {
                Title = request.Topic ?? "未知主题",
                Description = request.Description,
                Questions = new List<GeneratedQuestionDto>(),
                GeneratedAt = DateTime.UtcNow,
                QualityScore = 1
            });
        }
    }

    /// <summary>
    /// 解析优化建议响应
    /// </summary>
    /// <param name="llmResponse">LLM响应</param>
    /// <returns>优化结果</returns>
    private SurveyOptimizationResult ParseOptimizationResponse(string llmResponse)
    {
        // 简单解析，实际可以更复杂
        var suggestions = new List<OptimizationSuggestion>
        {
            new OptimizationSuggestion
            {
                Type = "General",
                Content = llmResponse,
                Priority = 3
            }
        };

        return new SurveyOptimizationResult
        {
            Suggestions = suggestions,
            OverallScore = 7,
            ExpectedImprovement = "基于LLM分析的优化建议"
        };
    }

    /// <summary>
    /// 解析洞察分析响应
    /// </summary>
    /// <param name="llmResponse">LLM响应</param>
    /// <param name="surveyDto">问卷信息</param>
    /// <returns>洞察结果</returns>
    private SurveyInsightResult ParseInsightResponse(string llmResponse, SurveyDto surveyDto)
    {
        try
        {
            // 尝试从响应中提取结构化信息
            var keyFindings = ExtractKeyFindings(llmResponse);
            var recommendedActions = ExtractRecommendedActions(llmResponse);
            var qualityScore = CalculateDataQualityScore(surveyDto, llmResponse);

            return new SurveyInsightResult
            {
                Insights = llmResponse,
                DataQualityScore = qualityScore,
                KeyFindings = keyFindings,
                RecommendedActions = recommendedActions
            };
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "解析洞察响应时出现错误，使用默认解析");
            
            return new SurveyInsightResult
            {
                Insights = llmResponse,
                DataQualityScore = 7,
                KeyFindings = new List<string> { "基于AI分析的专业洞察" },
                RecommendedActions = new List<string> { "建议根据分析结果优化问卷设计" }
            };
        }
    }

    /// <summary>
    /// 从响应中提取关键发现
    /// </summary>
    /// <param name="response">LLM响应</param>
    /// <returns>关键发现列表</returns>
    private List<string> ExtractKeyFindings(string response)
    {
        var findings = new List<string>();
        
        // 查找关键发现相关的段落
        var patterns = new[] { "关键洞察", "主要发现", "重要发现", "核心洞察" };
        
        foreach (var pattern in patterns)
        {
            var index = response.IndexOf(pattern, StringComparison.OrdinalIgnoreCase);
            if (index >= 0)
            {
                // 提取该段落的内容
                var section = ExtractSection(response, index);
                var items = ExtractListItems(section);
                findings.AddRange(items);
                break;
            }
        }
        
        return findings.Any() ? findings : new List<string> { "基于AI分析的专业洞察" };
    }

    /// <summary>
    /// 从响应中提取建议行动
    /// </summary>
    /// <param name="response">LLM响应</param>
    /// <returns>建议行动列表</returns>
    private List<string> ExtractRecommendedActions(string response)
    {
        var actions = new List<string>();
        
        // 查找建议相关的段落
        var patterns = new[] { "优化建议", "行动建议", "改进建议", "建议" };
        
        foreach (var pattern in patterns)
        {
            var index = response.IndexOf(pattern, StringComparison.OrdinalIgnoreCase);
            if (index >= 0)
            {
                var section = ExtractSection(response, index);
                var items = ExtractListItems(section);
                actions.AddRange(items);
                break;
            }
        }
        
        return actions.Any() ? actions : new List<string> { "建议根据分析结果优化问卷设计" };
    }

    /// <summary>
    /// 提取文本段落
    /// </summary>
    /// <param name="text">完整文本</param>
    /// <param name="startIndex">开始位置</param>
    /// <returns>段落内容</returns>
    private string ExtractSection(string text, int startIndex)
    {
        var endIndex = text.IndexOf("###", startIndex + 1);
        if (endIndex == -1)
        {
            endIndex = text.IndexOf("##", startIndex + 1);
        }
        if (endIndex == -1)
        {
            endIndex = text.Length;
        }
        
        return text.Substring(startIndex, endIndex - startIndex);
    }

    /// <summary>
    /// 从段落中提取列表项
    /// </summary>
    /// <param name="section">段落内容</param>
    /// <returns>列表项</returns>
    private List<string> ExtractListItems(string section)
    {
        var items = new List<string>();
        var lines = section.Split('\n', StringSplitOptions.RemoveEmptyEntries);
        
        foreach (var line in lines)
        {
            var trimmed = line.Trim();
            if (trimmed.StartsWith("-") || trimmed.StartsWith("•") || 
                Regex.IsMatch(trimmed, @"^\d+\."))
            {
                var content = Regex.Replace(trimmed, @"^[-•\d\.\s]+", "").Trim();
                if (!string.IsNullOrEmpty(content) && content.Length > 5)
                {
                    items.Add(content);
                }
            }
        }
        
        return items;
    }

    /// <summary>
    /// 计算数据质量评分
    /// </summary>
    /// <param name="surveyDto">问卷信息</param>
    /// <param name="analysisResponse">分析响应</param>
    /// <returns>质量评分(1-10)</returns>
    private int CalculateDataQualityScore(SurveyDto surveyDto, string analysisResponse)
    {
        var score = 5; // 基础分数
        
        // 基于问卷基本指标调整分数
        if (surveyDto.QuestionCount >= 5 && surveyDto.QuestionCount <= 20)
        {
            score += 1; // 题目数量合理
        }
        
        if (surveyDto.ResponseCount > 10)
        {
            score += 1; // 有足够的回答数据
        }
        
        if (surveyDto.ResponseCount > 50)
        {
            score += 1; // 回答数据充足
        }
        
        // 基于分析内容调整分数
        if (analysisResponse.Contains("质量") && analysisResponse.Contains("良好"))
        {
            score += 1;
        }
        
        if (analysisResponse.Contains("建议") && analysisResponse.Length > 500)
        {
            score += 1; // 分析内容详细
        }
        
        return Math.Max(1, Math.Min(10, score));
    }

    /// <summary>
    /// 估算Token数量
    /// </summary>
    /// <param name="text">文本</param>
    /// <returns>预估Token数</returns>
    private int EstimateTokenCount(string text)
    {
        if (string.IsNullOrEmpty(text))
            return 0;

        // 简单估算：1个Token约等于4个字符（英文）或1-2个中文字符
        var chineseChars = Regex.Matches(text, @"[\u4e00-\u9fff]").Count;
        var otherChars = text.Length - chineseChars;
        
        return (int)(chineseChars * 1.5 + otherChars / 4.0);
    }

    /// <summary>
    /// 计算生成质量评分
    /// </summary>
    /// <param name="surveyData">问卷数据</param>
    /// <returns>质量评分（1-10）</returns>
    private int CalculateQualityScore(dynamic surveyData)
    {
        var score = 5; // 基础分

        try
        {
            // 有标题和描述 +1
            if (!string.IsNullOrEmpty((string?)surveyData?.title) && 
                !string.IsNullOrEmpty((string?)surveyData?.description))
            {
                score += 1;
            }

            // 题目数量合理 +1
            if (surveyData?.questions != null)
            {
                var questionCount = ((System.Collections.IEnumerable)surveyData.questions).Cast<object>().Count();
                if (questionCount >= 3 && questionCount <= 20)
                {
                    score += 1;
                }
            }

            // 题目类型多样 +1
            // 题目有描述 +1
            // 选择题有选项 +1

            score = Math.Min(score, 10);
        }
        catch
        {
            // 解析失败，使用基础分
        }

        return score;
    }

    /// <summary>
    /// 保存生成的问卷及题目
    /// </summary>
    /// <param name="generatedSurvey">生成的问卷数据</param>
    /// <param name="request">原始生成请求</param>
    /// <param name="llmRawOutput">LLM原始输出内容</param>
    /// <returns>保存后的问卷DTO</returns>
    private async Task<SurveyDto> SaveGeneratedSurveyAsync(GeneratedSurveyDto generatedSurvey, GenerateSurveyRequest request, string llmRawOutput)
    {
        try
        {
            _logger.LogInformation("开始保存生成的问卷：{Title}", generatedSurvey.Title);

            // 创建问卷实体
            var createSurveyDto = new CreateSurveyDto
            {
                Title = generatedSurvey.Title,
                Description = generatedSurvey.Description,
                AccessType = SurveyAccessType.Public,
                IsTemplate = false,
                LLMPrompt = generatedSurvey.UsedPrompt,
                LLMRawOutput = llmRawOutput,
                CategoryId = request.CategoryId,
            };

            // 保存问卷
            var savedSurvey = await _surveyService.CreateAsync(createSurveyDto);

            _logger.LogInformation("问卷已保存，ID：{SurveyId}", savedSurvey.Id);

            // 保存题目（带验证和重试机制）
            var validationErrors = new List<string>();
            var validatedQuestions = new List<GeneratedQuestionDto>();

            foreach (var generatedQuestion in generatedSurvey.Questions)
            {
                var questionType = MapStringToQuestionType(generatedQuestion.Type);
                
                var createQuestionDto = new CreateQuestionDto
                {
                    SurveyId = savedSurvey.Id,
                    Title = generatedQuestion.Title,
                    Description = generatedQuestion.Description,
                    Type = questionType,
                    OrderIndex = generatedQuestion.OrderIndex,
                    IsRequired = generatedQuestion.IsRequired,
                    LLMGenerated = true
                };

                // 添加选项
                if (generatedQuestion.Options?.Any() == true)
                {
                    createQuestionDto.Options = generatedQuestion.Options.Select(o => new CreateQuestionOptionDto
                    {
                        Text = o.Text,
                        Value = o.Value ?? o.Text,
                        OrderIndex = o.OrderIndex,
                        IsOther = false
                    }).ToList();
                }

                try
                {
                    await _questionService.CreateAsync(createQuestionDto);
                    validatedQuestions.Add(generatedQuestion);
                }
                catch (BusinessException ex) when (ex.Message.Contains("题目验证失败"))
                {
                    _logger.LogWarning("题目验证失败：{Title} - {Error}", generatedQuestion.Title, ex.Message);
                    validationErrors.Add($"题目\"{generatedQuestion.Title}\"：{ex.Message}");
                }
            }

            // 如果有验证错误，尝试修正
            if (validationErrors.Any())
            {
                _logger.LogInformation("存在 {ErrorCount} 个题目验证错误，尝试AI修正", validationErrors.Count);
                
                var correctionResult = await TryCorrectQuestionsAsync(request, generatedSurvey, validationErrors, savedSurvey.Id);
                
                if (correctionResult.HasCorrectedQuestions)
                {
                    validatedQuestions.AddRange(correctionResult.CorrectedQuestions);
                    _logger.LogInformation("AI修正成功，新增 {CorrectedCount} 个题目", correctionResult.CorrectedQuestions.Count);
                }
                else
                {
                    _logger.LogWarning("AI修正失败，部分题目无法保存：{Errors}", string.Join("；", validationErrors));
                }
            }

            _logger.LogInformation("问卷及题目保存完成，问卷ID：{SurveyId}，题目数量：{QuestionCount}", 
                savedSurvey.Id, generatedSurvey.Questions.Count);

            return savedSurvey;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "保存生成的问卷失败：{Title}", generatedSurvey.Title);
            throw new BusinessException($"保存问卷失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 将字符串类型映射为QuestionType枚举
    /// </summary>
    /// <param name="typeString">类型字符串</param>
    /// <returns>QuestionType枚举</returns>
    private QuestionType MapStringToQuestionType(string typeString)
    {
        if (string.IsNullOrEmpty(typeString))
            return QuestionType.Text;

        return typeString.ToLower() switch
        {
            "singlechoice" or "single" or "radio" => QuestionType.SingleChoice,
            "multiplechoice" or "multiple" or "checkbox" => QuestionType.MultipleChoice,
            "text" or "input" => QuestionType.Text,
            "textarea" or "longtext" => QuestionType.Textarea,
            "number" or "numeric" => QuestionType.Number,
            "rating" or "rate" => QuestionType.Rating,
            "date" => QuestionType.Date,
            "time" => QuestionType.Time,
            "datetime" => QuestionType.DateTime,
            "matrix" => QuestionType.Matrix,
            "ranking" or "rank" => QuestionType.Ranking,
            _ => QuestionType.Text
        };
    }

    /// <summary>
    /// 尝试修正验证失败的题目
    /// </summary>
    /// <param name="originalRequest">原始请求</param>
    /// <param name="originalSurvey">原始生成的问卷</param>
    /// <param name="validationErrors">验证错误列表</param>
    /// <param name="surveyId">问卷ID</param>
    /// <returns>修正结果</returns>
    private async Task<QuestionCorrectionResult> TryCorrectQuestionsAsync(
        GenerateSurveyRequest originalRequest, 
        GeneratedSurveyDto originalSurvey, 
        List<string> validationErrors, 
        int surveyId)
    {
        try
        {
            // 获取LLM设置
            var llmSettings = await _settingsService.GetLLMSettingsAsync();

            // 构建修正提示词
            var correctionPrompt = BuildCorrectionPrompt(originalRequest, originalSurvey, validationErrors);

            // 调用LLM生成修正后的题目
            var llmResponse = await _llmAssistant.GenerateContentAsync(correctionPrompt, llmSettings.MaxTokens);

            // 解析修正后的题目
            var correctedQuestions = await ParseCorrectionResponseAsync(llmResponse);

            // 验证并保存修正后的题目
            var savedQuestions = new List<GeneratedQuestionDto>();
            foreach (var correctedQuestion in correctedQuestions)
            {
                var questionType = MapStringToQuestionType(correctedQuestion.Type);
                
                var createQuestionDto = new CreateQuestionDto
                {
                    SurveyId = surveyId,
                    Title = correctedQuestion.Title,
                    Description = correctedQuestion.Description,
                    Type = questionType,
                    OrderIndex = correctedQuestion.OrderIndex,
                    IsRequired = correctedQuestion.IsRequired,
                    LLMGenerated = true
                };

                // 添加选项
                if (correctedQuestion.Options?.Any() == true)
                {
                    createQuestionDto.Options = correctedQuestion.Options.Select(o => new CreateQuestionOptionDto
                    {
                        Text = o.Text,
                        Value = o.Value ?? o.Text,
                        OrderIndex = o.OrderIndex,
                        IsOther = false
                    }).ToList();
                }

                try
                {
                    await _questionService.CreateAsync(createQuestionDto);
                    savedQuestions.Add(correctedQuestion);
                    _logger.LogInformation("修正题目保存成功：{Title}", correctedQuestion.Title);
                }
                catch (BusinessException ex)
                {
                    _logger.LogWarning("修正题目仍然验证失败：{Title} - {Error}", correctedQuestion.Title, ex.Message);
                }
            }

            return new QuestionCorrectionResult
            {
                HasCorrectedQuestions = savedQuestions.Any(),
                CorrectedQuestions = savedQuestions,
                RemainingErrors = savedQuestions.Count < correctedQuestions.Count 
                    ? new List<string> { "部分修正题目仍然验证失败" } 
                    : new List<string>()
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "AI修正题目过程中发生错误");
            return new QuestionCorrectionResult
            {
                HasCorrectedQuestions = false,
                CorrectedQuestions = new List<GeneratedQuestionDto>(),
                RemainingErrors = new List<string> { $"AI修正失败：{ex.Message}" }
            };
        }
    }

    /// <summary>
    /// 构建修正提示词
    /// </summary>
    /// <param name="originalRequest">原始请求</param>
    /// <param name="originalSurvey">原始生成的问卷</param>
    /// <param name="validationErrors">验证错误列表</param>
    /// <returns>修正提示词</returns>
    private string BuildCorrectionPrompt(GenerateSurveyRequest originalRequest, GeneratedSurveyDto originalSurvey, List<string> validationErrors)
    {
        var promptBuilder = new StringBuilder();

        promptBuilder.AppendLine("你是一个问卷设计专家，需要修正以下问卷题目的验证错误：");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine($"原始问卷主题：{originalRequest.Topic}");
        promptBuilder.AppendLine();
        
        promptBuilder.AppendLine("发现的验证错误：");
        foreach (var error in validationErrors)
        {
            promptBuilder.AppendLine($"- {error}");
        }
        promptBuilder.AppendLine();

        promptBuilder.AppendLine("请根据以下验证规则修正题目：");
        promptBuilder.AppendLine("1. 单选题和多选题必须至少包含2个有效选项");
        promptBuilder.AppendLine("2. 选项文本不能为空且不能重复");
        promptBuilder.AppendLine("3. 矩阵题至少需要2个行选项，并需要配置列选项设置");
        promptBuilder.AppendLine("4. 排序题至少需要2个选项");
        promptBuilder.AppendLine("5. 评分题如果有自定义标签，标签不能为空");
        promptBuilder.AppendLine();

        promptBuilder.AppendLine("请只修正有错误的题目，保持题目的原始意图，并以JSON格式返回修正后的题目：");
        promptBuilder.AppendLine();
        promptBuilder.AppendLine("期望的JSON格式：");
        promptBuilder.AppendLine(@"{
  ""correctedQuestions"": [
    {
      ""title"": ""题目标题"",
      ""description"": ""题目描述"",
      ""type"": ""题目类型"",
      ""isRequired"": true/false,
      ""orderIndex"": 排序索引,
      ""options"": [
        {
          ""text"": ""选项文本"",
          ""value"": ""选项值"",
          ""orderIndex"": 1
        }
      ]
    }
  ]
}");

        return promptBuilder.ToString();
    }

    /// <summary>
    /// 解析修正响应
    /// </summary>
    /// <param name="llmResponse">LLM响应</param>
    /// <returns>修正后的题目列表</returns>
    private Task<List<GeneratedQuestionDto>> ParseCorrectionResponseAsync(string llmResponse)
    {
        try
        {
            // 尝试从响应中提取JSON
            var jsonMatch = Regex.Match(llmResponse, @"\{[\s\S]*\}", RegexOptions.Multiline);
            var jsonContent = jsonMatch.Success ? jsonMatch.Value : llmResponse;

            // 解析JSON
            var correctionData = JsonConvert.DeserializeObject<dynamic>(jsonContent);

            var result = new List<GeneratedQuestionDto>();

            // 解析修正后的题目
            if (correctionData?.correctedQuestions != null)
            {
                foreach (var questionData in correctionData.correctedQuestions)
                {
                    var question = new GeneratedQuestionDto
                    {
                        Title = questionData?.title ?? "",
                        Description = questionData?.description,
                        Type = questionData?.type ?? "Text",
                        IsRequired = questionData?.isRequired ?? false,
                        OrderIndex = questionData?.orderIndex ?? 0,
                        Options = new List<GeneratedQuestionOptionDto>()
                    };

                    // 解析选项
                    if (questionData?.options != null)
                    {
                        int optionIndex = 1;
                        foreach (var optionData in questionData.options)
                        {
                            question.Options.Add(new GeneratedQuestionOptionDto
                            {
                                Text = optionData?.text ?? "",
                                Value = optionData?.value,
                                OrderIndex = optionIndex++
                            });
                        }
                    }

                    result.Add(question);
                }
            }

            return Task.FromResult(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "解析修正响应失败");
            return Task.FromResult(new List<GeneratedQuestionDto>());
        }
    }

    #endregion

    #region AI扩题功能

    /// <summary>
    /// AI扩题功能
    /// </summary>
    /// <param name="request">扩题请求</param>
    /// <returns>扩题结果</returns>
    public async Task<ExpandQuestionsResult> ExpandQuestionsAsync(ExpandQuestionsRequest request)
    {
        try
        {
            _logger.LogInformation("开始AI扩题，问卷ID：{SurveyId}，扩展数量：{ExpandCount}", request.Id, request.ExpandCount);

            // 获取问卷信息
            var survey = await _surveyService.GetAsync(request.Id);
            if (survey == null)
            {
                throw new BusinessException("问卷不存在");
            }

            // 获取现有题目
            var existingQuestions = await _questionService.GetQuestionsBySurveyIdAsync(request.Id);

            // 分析现有问卷风格
            var styleAnalysis = request.MaintainStyle ? await AnalyzeSurveyStyleAsync(survey, existingQuestions) : null;

            // 构建扩题提示词
            var prompt = BuildExpandQuestionsPrompt(survey, existingQuestions, request, styleAnalysis);

            // 调用LLM生成扩展题目
            var llmResponse = await _llmAssistant.GenerateContentAsync(prompt, 2000);

            // 解析LLM响应
            var generatedQuestions = await ParseExpandQuestionsResponseAsync(llmResponse, request.Id);

            // 计算插入位置并更新排序索引
            var questionsWithOrder = CalculateInsertPositions(generatedQuestions, existingQuestions, request.InsertPosition);

            // 保存生成的题目到数据库
            var savedQuestions = new List<QuestionDto>();
            foreach (var question in questionsWithOrder)
            {
                var createDto = _mapper.Map<CreateQuestionDto>(question);
                createDto.SurveyId = request.Id;
                question.LLMGenerated = true;

                var savedQuestion = await _questionService.CreateAsync(createDto);
                savedQuestions.Add(savedQuestion);
            }

            // 更新问卷的题目数量（通过重新计算）
            // 注意：这里可能需要在SurveyService中添加UpdateQuestionCountAsync方法
            // 暂时跳过这个步骤，因为题目创建时会自动更新统计

            var result = new ExpandQuestionsResult
            {
                GeneratedQuestions = savedQuestions,
                ExpandDescription = $"基于现有{existingQuestions.Count}道题目，成功扩展了{savedQuestions.Count}道新题目",
                StyleAnalysis = styleAnalysis,
                UsedPrompt = prompt,
                LLMRawOutput = llmResponse,
                SuccessCount = savedQuestions.Count,
                Suggestions = GenerateExpandSuggestions(survey, savedQuestions)
            };

            _logger.LogInformation("AI扩题完成，成功生成{Count}道题目", savedQuestions.Count);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "AI扩题失败，问卷ID：{SurveyId}", request.Id);
            throw new BusinessException($"AI扩题失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 分析问卷风格
    /// </summary>
    /// <param name="survey">问卷信息</param>
    /// <param name="existingQuestions">现有题目</param>
    /// <returns>风格分析结果</returns>
    private async Task<string> AnalyzeSurveyStyleAsync(SurveyDto survey, List<QuestionDto> existingQuestions)
    {
        if (!existingQuestions.Any())
        {
            return "问卷暂无题目，无法分析风格";
        }

        var analysisPrompt = $@"
请分析以下问卷的风格特征：

问卷标题：{survey.Title}
问卷描述：{survey.Description}

现有题目：
{string.Join("\n", existingQuestions.Select((q, i) => $"{i + 1}. [{GetQuestionTypeName(q.Type.ToString())}] {q.Title}"))}

请从以下维度分析问卷风格：
1. 语言风格（正式/非正式、专业/通俗）
2. 题目长度特征
3. 题目类型偏好
4. 逻辑结构特点
5. 目标受众特征

请用简洁的语言总结风格特征，用于指导后续题目生成。
";

        try
        {
            var response = await _llmAssistant.GenerateContentAsync(analysisPrompt, 500);
            return response;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "分析问卷风格失败");
            return "风格分析失败，将使用默认风格";
        }
    }

    /// <summary>
    /// 构建扩题提示词
    /// </summary>
    /// <param name="survey">问卷信息</param>
    /// <param name="existingQuestions">现有题目</param>
    /// <param name="request">扩题请求</param>
    /// <param name="styleAnalysis">风格分析</param>
    /// <returns>提示词</returns>
    private string BuildExpandQuestionsPrompt(SurveyDto survey, List<QuestionDto> existingQuestions, ExpandQuestionsRequest request, string? styleAnalysis)
    {
        var prompt = new StringBuilder();

        prompt.AppendLine("你是一个专业的问卷设计专家，需要为现有问卷扩展新的题目。");
        prompt.AppendLine();

        // 问卷基本信息
        prompt.AppendLine("## 问卷信息");
        prompt.AppendLine($"标题：{survey.Title}");
        if (!string.IsNullOrEmpty(survey.Description))
        {
            prompt.AppendLine($"描述：{survey.Description}");
        }
        prompt.AppendLine($"现有题目数量：{existingQuestions.Count}");
        prompt.AppendLine();

        // 现有题目列表
        if (existingQuestions.Any())
        {
            prompt.AppendLine("## 现有题目");
            foreach (var question in existingQuestions.OrderBy(q => q.OrderIndex))
            {
                prompt.AppendLine($"{question.OrderIndex + 1}. [{GetQuestionTypeName(question.Type.ToString())}] {question.Title}");
                if (!string.IsNullOrEmpty(question.Description))
                {
                    prompt.AppendLine($"   描述：{question.Description}");
                }
            }
            prompt.AppendLine();
        }

        // 风格分析
        if (!string.IsNullOrEmpty(styleAnalysis))
        {
            prompt.AppendLine("## 问卷风格分析");
            prompt.AppendLine(styleAnalysis);
            prompt.AppendLine();
        }

        // 扩展要求
        prompt.AppendLine("## 扩展要求");
        prompt.AppendLine($"需要扩展的题目数量：{request.ExpandCount}");
        
        if (!string.IsNullOrEmpty(request.ExpandDirection))
        {
            prompt.AppendLine($"扩展方向：{request.ExpandDirection}");
        }

        if (request.PreferredQuestionTypes?.Any() == true)
        {
            prompt.AppendLine($"偏好题型：{string.Join("、", request.PreferredQuestionTypes.Select(GetQuestionTypeName))}");
        }

        if (!string.IsNullOrEmpty(request.CustomPrompt))
        {
            prompt.AppendLine($"自定义要求：{request.CustomPrompt}");
        }

        prompt.AppendLine();

        // 生成指导
        prompt.AppendLine("## 生成指导");
        prompt.AppendLine("1. 扩展的题目应该与现有题目形成良好的逻辑关系和补充");
        prompt.AppendLine("2. 保持与现有题目风格的一致性");
        prompt.AppendLine("3. 避免与现有题目重复或过于相似");
        prompt.AppendLine("4. 确保题目表述清晰、无歧义");
        prompt.AppendLine("5. 选项设计要合理、全面");
        prompt.AppendLine();

        // 输出格式要求
        prompt.AppendLine("请按以下JSON格式输出扩展的题目：");
        prompt.AppendLine(@"{
  ""questions"": [
    {
      ""title"": ""题目标题"",
      ""description"": ""题目描述（可选）"",
      ""type"": ""题目类型（SingleChoice/MultipleChoice/Text/Textarea/Rating/Number等）"",
      ""isRequired"": true/false,
      ""options"": [
        {
          ""text"": ""选项文本"",
          ""value"": ""选项值（可选）""
        }
      ]
    }
  ]
}");

        return prompt.ToString();
    }

    /// <summary>
    /// 解析扩题响应
    /// </summary>
    /// <param name="llmResponse">LLM响应</param>
    /// <param name="surveyId">问卷ID</param>
    /// <returns>生成的题目列表</returns>
    private Task<List<GeneratedQuestionDto>> ParseExpandQuestionsResponseAsync(string llmResponse, int surveyId)
    {
        try
        {
            var result = new List<GeneratedQuestionDto>();

            // 提取JSON部分
            var jsonMatch = Regex.Match(llmResponse, @"\{.*\}", RegexOptions.Singleline);
            if (!jsonMatch.Success)
            {
                throw new BusinessException("LLM响应格式不正确，无法解析JSON");
            }

            var jsonContent = jsonMatch.Value;
            var responseData = JsonConvert.DeserializeObject<dynamic>(jsonContent);

            if (responseData?.questions != null)
            {
                int orderIndex = 1;
                foreach (var questionData in responseData.questions)
                {
                    var question = new GeneratedQuestionDto
                    {
                        Title = questionData?.title ?? "",
                        Description = questionData?.description,
                        Type = questionData?.type ?? "Text",
                        IsRequired = questionData?.isRequired ?? false,
                        OrderIndex = orderIndex++,
                        Options = new List<GeneratedQuestionOptionDto>()
                    };

                    // 解析选项
                    if (questionData?.options != null)
                    {
                        int optionIndex = 1;
                        foreach (var optionData in questionData.options)
                        {
                            question.Options.Add(new GeneratedQuestionOptionDto
                            {
                                Text = optionData?.text ?? "",
                                Value = optionData?.value,
                                OrderIndex = optionIndex++
                            });
                        }
                    }

                    result.Add(question);
                }
            }

            return Task.FromResult(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "解析扩题响应失败");
            throw new BusinessException($"解析AI响应失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 计算插入位置并更新排序索引
    /// </summary>
    /// <param name="newQuestions">新题目</param>
    /// <param name="existingQuestions">现有题目</param>
    /// <param name="insertPosition">插入位置</param>
    /// <returns>带有正确排序索引的题目列表</returns>
    private List<GeneratedQuestionDto> CalculateInsertPositions(List<GeneratedQuestionDto> newQuestions, List<QuestionDto> existingQuestions, string insertPosition)
    {
        var maxOrderIndex = existingQuestions.Any() ? existingQuestions.Max(q => q.OrderIndex) : 0;

        switch (insertPosition.ToLower())
        {
            case "beginning":
                // 插入到开头，需要更新现有题目的排序索引（这里只返回新题目的索引）
                for (int i = 0; i < newQuestions.Count; i++)
                {
                    newQuestions[i].OrderIndex = i + 1;
                }
                break;

            case "middle":
                // 插入到中间
                var middleIndex = existingQuestions.Count / 2;
                for (int i = 0; i < newQuestions.Count; i++)
                {
                    newQuestions[i].OrderIndex = middleIndex + i + 1;
                }
                break;

            case "end":
            default:
                // 插入到末尾
                for (int i = 0; i < newQuestions.Count; i++)
                {
                    newQuestions[i].OrderIndex = maxOrderIndex + i + 1;
                }
                break;
        }

        return newQuestions;
    }

    /// <summary>
    /// 生成扩展建议
    /// </summary>
    /// <param name="survey">问卷信息</param>
    /// <param name="generatedQuestions">生成的题目</param>
    /// <returns>建议列表</returns>
    private List<string> GenerateExpandSuggestions(SurveyDto survey, List<QuestionDto> generatedQuestions)
    {
        var suggestions = new List<string>();

        if (generatedQuestions.Any())
        {
            suggestions.Add("建议在发布前预览问卷，确保题目逻辑流畅");
            suggestions.Add("可以根据需要调整题目顺序和必填设置");
            
            var questionTypes = generatedQuestions.Select(q => q.Type.ToString()).Distinct().ToList();
            if (questionTypes.Count > 1)
            {
                suggestions.Add("新增题目包含多种类型，有助于收集更丰富的数据");
            }

            if (generatedQuestions.Any(q => q.Type.ToString() == "Textarea"))
            {
                suggestions.Add("包含开放性题目，建议在分析时重点关注文本回答的质量");
            }
        }

        return suggestions;
    }

    /// <summary>
    /// 获取题目类型中文名称
    /// </summary>
    /// <param name="questionType">题目类型</param>
    /// <returns>中文名称</returns>
    private static string GetQuestionTypeName(string questionType)
    {
        return questionType switch
        {
            "SingleChoice" => "单选题",
            "MultipleChoice" => "多选题",
            "Text" => "填空题",
            "Number" => "数字题",
            "Rating" => "评分题",
            "Date" => "日期题",
            "Time" => "时间题",
            "DateTime" => "日期时间题",
            "Textarea" => "长文本题",
            "Matrix" => "矩阵题",
            "Ranking" => "排序题",
            _ => questionType
        };
    }

    #endregion
}

/// <summary>
/// 题目修正结果
/// </summary>
public class QuestionCorrectionResult
{
    /// <summary>
    /// 是否有修正成功的题目
    /// </summary>
    public bool HasCorrectedQuestions { get; set; }

    /// <summary>
    /// 修正成功的题目列表
    /// </summary>
    public List<GeneratedQuestionDto> CorrectedQuestions { get; set; } = new();

    /// <summary>
    /// 剩余的错误
    /// </summary>
    public List<string> RemainingErrors { get; set; } = new();
}
